package com.quark.framework.service;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.quark.framework.caller.QuarkCallResult;
import com.quark.framework.caller.QuarkCallerBase;
import com.quark.framework.utility.QuarkLog;

public class QuarkServiceBase extends QuarkCallerBase{
	//mapping helper
	private static Map<String, String> makeSimpleMap(Map<String, String[]> map)
	{
		Map<String, String> retMap = new HashMap<String, String>();
		Iterator<String> keyList = map.keySet().iterator();
		while(keyList.hasNext())
		{
			String theKey = keyList.next();			
			retMap.put(theKey, map.get(theKey)[0]);
		}
		return retMap;
	}
	
	//create ServiceModule Client javascript call code
	public String createAjaxCall()
	{
		StringBuffer buffer = new StringBuffer();
		Method[] methods = getClass().getMethods();
		buffer.append("/*");
		buffer.append(" " + getClass().getCanonicalName() + " Module Client Javascript Code");
		buffer.append("*/");
		buffer.append("\r\n");
		for(int i = 0; i < methods.length; i ++)
		{
			Method m = methods[i];
			Class<?> parameters[] = m.getParameterTypes();
			buffer.append("function ajax" + m.getClass().getName() + "(");
			for(int j = 0; j < parameters.length; j++)
			{
				buffer.append("arg" + j);
				if( j < parameters.length - 1)
				{
					buffer.append(",");
				}
			}
			buffer.append(")");
			buffer.append("{}");
			//FIXME:Add function body.
		}
		return buffer.toString();
	}
	
	public Object workA(String name, Map<String, String> map)
	{
		QuarkCallResult rst = call(name, map);
		if(rst.isSuccessful())
		{
			return rst.getResult();
		}
		else
		{
			QuarkLog.logToFile(rst.getException());
			return null;
		}
	}
	
	public Object work(String name, Map<String, String[]> map)
	{
		return workA(name, makeSimpleMap(map));
	}
}
